package info.liujiachen.security.test.controller;

import info.liujiachen.security.test.service.JwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class JwtController {

    @Autowired
    private JwtService jwtService;

    @RequestMapping({"/","/home"})
    public String home() {
        return "Home Page";
    }

    @RequestMapping({"/token"})
    public String token(HttpServletRequest request) {
        String token = request.getHeader("Authorization").substring(6);
        return token;
    }

    @PreAuthorize("hasAuthority('user')")
    @RequestMapping({"/user"})
    public String user(HttpServletRequest request) {
//        String token = request.getHeader("Authorization").substring(6);
//        DecodedJWT jwt = JWT.decode(token);
//        String username = jwt.getSubject();
        return jwtService.user();
    }

    @PreAuthorize("hasAuthority('test')")
    @RequestMapping({"/test"})
    public String test() {
        return jwtService.test();
    }

    @PreAuthorize("hasAuthority('admin')")
    @RequestMapping({"/admin"})
    public String admin() {
        return jwtService.admin();
    }

}
